//
//  MYTabBarButton.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-21.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "MYTabBarButton.h"
#import "MYBadgeView.h"
#define MYImageRadio 0.7 //image在TabBarButton中的高度比例
#define MYTabBarButtonMargin 10 //间隙
@interface MYTabBarButton ()
@property (nonatomic, weak) MYBadgeView *badgeView;
@end
@implementation MYTabBarButton
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.imageView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:12];
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    }
    return self;
}
- (MYBadgeView *)badgeView
{
    if (nil == _badgeView) {
        MYBadgeView *badgeView = [[MYBadgeView alloc] init];
        [self addSubview:badgeView];
        _badgeView = badgeView;
    }
    return _badgeView;
}
- (void)setItem:(UITabBarItem *)item
{
    _item = item;
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
    [self addObject:_item newValueKey:@"badgeValue"];
    [self addObject:_item newValueKey:@"image"];
    [self addObject:_item newValueKey:@"selectedImage"];
    [self addObject:_item newValueKey:@"title"];
}
#pragma 添加KVO观察属性的变化
- (void)addObject:(UITabBarItem *)object newValueKey:(NSString *)newValueKey
{
    [object addObserver:self forKeyPath:newValueKey options:NSKeyValueObservingOptionNew context:nil];
}
// 只要item的badgeValue有新值改变就会调用,KVO响应方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    self.badgeView.badgeValue = _item.badgeValue;
    [self setImage:_item.image forState:UIControlStateNormal];
    [self setImage:_item.selectedImage forState:UIControlStateSelected];
    [self setTitle:_item.title forState:UIControlStateNormal];
}
- (void)dealloc
{
    [_item removeObserver:self forKeyPath:@"badgeValue"];
    [_item removeObserver:self forKeyPath:@"image"];
    [_item removeObserver:self forKeyPath:@"selectedImage"];
    [_item removeObserver:self forKeyPath:@"title"];
}
- (void)layoutSubviews
{
    [super layoutSubviews];;
    CGFloat imageX = 0;
    CGFloat imageY = 0;
    CGFloat imageH = self.height * MYImageRadio;
    CGFloat imageW = self.width;
    self.imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
    
    CGFloat titleY = imageH;
    CGFloat titleX = 0;
    CGFloat titleW = imageW;
    CGFloat titleH = self.height - imageH;
    self.titleLabel.frame = CGRectMake(titleX, titleY, titleW, titleH);
    
    //设置badgeView的frame
    self.badgeView.x = self.width - self.badgeView.width - MYTabBarButtonMargin;
}
- (void)setHighlighted:(BOOL)highlighted
{
}
@end
